#include "StdAfx.h"
#include "buddy_manager.h"
#include <algorithm4cpp/pinyin_util.h>

buddy_manager::buddy_manager(void)
: buddies_()
, searcher_()
{
}

buddy_manager::~buddy_manager(void)
{
}

void buddy_manager::add_buddy( const buddy & b )
{
	pair<buddy_map::iterator, bool> result = buddies_.insert(make_pair(b.id(),b));
	if ( ! result.second ) {
		return ;
	}

	searcher_.add_name_object( lexical_cast<wstring>( b.id() ), b.id() );

	add_name_tag( b.name(), b.id());
	add_name_tag( b.nick(), b.id());
}

void buddy_manager::remove_buddy( const buddy & b )
{
	buddy_map::iterator it = buddies_.find( b.id() );
	if ( it == buddies_.end() ) {
		return ;
	}
	searcher_.remove_named_object( lexical_cast<wstring>( b.id() ), b.id() );

	remove_name_tag( b.name(), b.id());
	remove_name_tag( b.nick(), b.id());
}

void buddy_manager::search_buddy( const wstring & key, buddy_set & buddies ) const
{
	tag_set tags;
	searcher_.search( key, tags );

	for ( tag_set::const_iterator it = tags.begin(); it != tags.end(); ++it ) {
		buddy_map::const_iterator buddy_it = buddies_.find( *it );
		if ( buddy_it != buddies_.end() ) {
			buddies.insert( buddy_it->second );
		}
	}
}

void buddy_manager::add_name_tag( const wstring & name, __int64 tag )
{
	searcher_.add_name_object( name, tag );

	set<wstring> pinyin = pinyin_util::chinese_to_pinyin( name );
	add_pinyin_tag(pinyin, name, tag);

	set<wstring> shengmu = pinyin_util::chinese_to_shengmu( name );
	add_pinyin_tag( shengmu, name, tag );
}

void buddy_manager::remove_name_tag( const wstring & name, __int64 tag )
{
	searcher_.remove_named_object( name, tag );

	set<wstring> pinyin = pinyin_util::chinese_to_pinyin( name );
	remove_pinyin_tag(pinyin, tag);
	

	set<wstring> shengmu = pinyin_util::chinese_to_shengmu( name );
	remove_pinyin_tag(shengmu, tag );
}

void buddy_manager::add_pinyin_tag( const set<wstring> &pinyin, const wstring & name, __int64 tag )
{
	if ( pinyin.empty() ) {
		return ;
	}

	BOOST_FOREACH( const wstring & p, pinyin )
	{
		if ( p != name ) {
			searcher_.add_name_object( p, tag );
		}
	}
}

void buddy_manager::remove_pinyin_tag( set<wstring> &pinyin, __int64 tag )
{
	if ( pinyin.empty() ) {
		return ;
	}

	BOOST_FOREACH( const wstring & p, pinyin )
	{
		searcher_.remove_named_object( p, tag );
	}
}